package com.jyw.business.obstacles.task;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.google.common.collect.Lists;
import com.jyw.business.obstacles.constant.OrderCurrStateConstant;
import com.jyw.business.obstacles.domain.ObsOrderFault;
import com.jyw.business.obstacles.domain.ObsOrderMake;
import com.jyw.business.obstacles.service.IObsOrderFaultService;
import com.jyw.business.obstacles.service.IObsOrderMakeService;
import com.jyw.common.constant.CacheConstants;
import com.jyw.common.core.redis.RedisCache;
import com.jyw.common.utils.DateUtils;
import com.jyw.system.domain.SysUserTeam;
import com.jyw.system.domain.vo.SysOrderReminderConfigVo;
import com.jyw.system.enums.MessageTypeEnum;
import com.jyw.system.service.ISysMessageService;
import com.jyw.system.service.ISysOrderReminderConfigService;
import com.jyw.system.service.ISysUserTeamService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 超时未完成定时任务
 */
@Component("processingTask")
@Slf4j
public class ProcessingTask {


    @Resource
    private ISysOrderReminderConfigService reminderConfigService;

    @Resource
    private IObsOrderFaultService orderFaultService;

    @Resource
    private IObsOrderMakeService makeService;

    @Resource
    private ISysUserTeamService userTeamService;

    @Resource
    private RedisCache redisCache;

    @Resource
    private ISysMessageService messageService;

    /**
     * 工单超时未完成通知
     * 工单标题
     * 故障分类
     * 报修科室
     * 处理人
     * 工单编号
     */
    public void remind() {
        SysOrderReminderConfigVo config = reminderConfigService.getDefaultConfig();
        //开启了超时完成提醒
        if (config.getCompleteTimeoutRemind() && config.getCompleteTimeoutMinute() != null &&
                config.getCompleteTimeoutInterval() != null && StrUtil.isNotEmpty(config.getCompleteTimeoutReminder())) {
            log.info("运行工单超时未完成提醒");
            //定义未完成状态
            List<String> processingState = Arrays.asList(OrderCurrStateConstant.PROCESSING, OrderCurrStateConstant.NOT_PASS_AUDIT);
            //读取超时几分钟
            Integer minute = config.getCompleteTimeoutMinute();
            //计算时间,小于该时间的都属于超时
            Date timeOutDate = DateUtils.addMinutes(DateUtils.getNowDate(), -minute);
            List<ObsOrderFault> list = orderFaultService
                    .lambdaQuery()
                    .le(ObsOrderFault::getCreateTime, timeOutDate)
                    .in(ObsOrderFault::getCurrState, processingState)
                    .list();
            if (CollUtil.isNotEmpty(list)) {
                Integer interval = config.getCompleteTimeoutInterval();
                String reminder = config.getCompleteTimeoutReminder();
                TimeUnit timeUnit=TimeUnit.SECONDS;
                Integer reminderSecond= interval*60;
                list.forEach(data -> {
                    String orderNum = data.getOrderNum();
                    String cacheKey=CacheConstants.PROCESSING_REMIND_KEY+orderNum;
                    String oldCache=redisCache.getCacheObject(cacheKey);
                    // 不存在缓存 发送消息
                    if(StrUtil.isEmpty(oldCache)){
                        //查询工单当前处理人
                        ObsOrderMake make = makeService.lambdaQuery().eq(ObsOrderMake::getOrderNum, orderNum).one();
                        if (make != null && make.getMakeUser() != null) {
                            Long makeUser= make.getMakeUser();
                            String msg = "工单号【"+orderNum+"】已超时未完成，请知晓";
                            Integer messageType = MessageTypeEnum.SYS_ORDER.getValue();
                            // 处理人
                            if(reminder.contains("1")){
                                messageService.sendSysMessage(messageType,makeUser,msg);
                            }
                            //查询当前处理人的组长
                            if(reminder.contains("2")){
                                List<Long> teamLeaders=userTeamService.getTeamLeaderByMark(makeUser);
                                messageService.sendBatchSysMessage(messageType,teamLeaders,msg);
                            }
                            redisCache.setCacheObject(cacheKey, orderNum,reminderSecond, timeUnit);
                        }
                    }
                });
            }
        }
    }
}
